import os
from typing import List

from database.mysqlhelper import MySqLHelper
from utils import doc_util, json_util, read_config

db = MySqLHelper()
config_path = os.path.join(read_config.data_path, 'common', 'config')

table_name = ' t_stock_info '
params_sql = ' f_code, f_name, f_exchange, f_total_hand, f_total_val, f_cir_val, f_pe , f_period '


# f_pe:市盈率
class StockDto:
    def __init__(self, code, name, exchange, total_hand, total_val, cir_val, pe, period):
        self.code = code
        self.name = name
        self.exchange = exchange
        self.total_hand = total_hand
        self.total_val = total_val
        self.cir_val = cir_val
        self.pe = pe
        self.period = period

    def __repr__(self):
        return repr(
            (self.code, self.name, self.exchange, self.total_hand, self.total_val, self.cir_val, self.pe))


# 格式化结果
def format_info(res):
    if not res:
        return
    return StockDto(str(res[0], encoding="utf-8"),
                    str(res[1], encoding="utf-8"),
                    int(res[2]), float(res[3]),
                    int(res[4]),
                    int(res[5]),
                    int(res[6]),
                    int(res[7]),
                    )


# 格式化结果
def format_one(res):
    if not res:
        return {}
    return {'code': str(res[0], encoding="utf-8"),
            'name': str(res[1], encoding="utf-8"),
            'exchange': int(res[2]),
            'total_hand': float(res[3]),
            'total_val': int(res[4]),
            'cir_val': int(res[5]),
            'pe': int(res[6]),
            'period': int(res[7])
            }


def get_values() -> str:
    vr = ' '
    for i in range(len(params_sql.split(','))):
        vr += '%s, '
    return vr[0:len(vr) - 1]


insert_sql = 'insert into ' + table_name + ' (' + params_sql + ') VALUES (' + get_values() + ') '
select_sql = 'select ' + params_sql + ' from ' + table_name


# 名称模糊查询
def select_by_name(name):
    sql = select_sql + ' where f_name like \'%' + name + '%\''
    return format_mul(db.selectall(sql))


# 获取一条
def select_by_code(code):
    # 增加多条
    sql = select_sql + ' where f_code = %s '
    return format_info(db.selectone(sql, (code)))


# 获取所有
def select_all() -> List[StockDto]:
    return format_mul(db.selectall(select_sql))


# 格式化结果
def format_mul(res):
    list = []
    for p in res:
        list.append(format_info(p))
    return list


# 初始化所有股票
def insert(stock_info):
    li = (stock_info['code'], stock_info['name'], stock_info['exchange'], 0, 0, 0, 0)
    return db.insertone(insert_sql, li)


# 初始化所有股票
def insertall():
    stock_dict = doc_util.get_a_doc_dict(os.path.join(config_path, '0.股票信息'), 'code')
    # 增加多条
    li = []
    for key in stock_dict:
        stock_info = json_util.to_json(stock_dict[key])
        li.append((stock_info['code'], stock_info['name'], stock_info['exchange'], 0, 0, 0))
    return db.insertmany(insert_sql, li)


# 所有股票
def selectall():
    return format_res(db.selectall(select_sql + ' order by f_id '))


# 所有股票
def select_order_sz():
    sql = select_sql + ' order by f_total_val desc'
    return format_res(db.selectall(sql))


# 获取一条
def selectone(code):
    # 增加多条
    sql = select_sql + ' where f_code = %s '
    return format_one(db.selectone(sql, (code)))


# 更新市值
def update_the_val(code, total_val, cir_val):
    sql1 = 'update t_stock_info set f_total_val = %s,f_cir_val = %s where f_code = %s  '
    return db.update(sql1, (total_val, cir_val, code))


# 更新周期
def update_the_period(code, period):
    sql1 = 'update t_stock_info set f_period = %s, where f_code = %s  '
    return db.update(sql1, (period, code))


# 格式化结果
def format_res(res):
    list = []
    for p in res:
        list.append(format_one(p))
    return list


# 名称模糊查询
def select_name_like(name):
    sql = select_sql + ' where f_name like \'%' + name + '%\''
    return format_res(db.selectall(sql))


if __name__ == '__main__':
    # print(select_name_like('锂'))
    print(selectall())
